/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.mqtt.client.paho

import cool.taomu.software.fig.crypto.Base64
import cool.taomu.software.fig.mqtt.client.paho.entity.SenderEntity
import cool.taomu.software.fig.mqtt.client.paho.inter.IMQTTSender
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import org.slf4j.LoggerFactory

class MQTTSender implements IMQTTSender {
    val LOG = LoggerFactory.getLogger(MQTTSender);

    override publish(SenderEntity sender) {
        LOG.info("mqtt sender info:" + sender.toString());
        try (var memoryPersistence = new MemoryPersistence()) {
            var mqttConnectOptions = new MqttConnectOptions();
            mqttConnectOptions.setCleanSession(true);
            mqttConnectOptions.setUserName(sender.username);
            mqttConnectOptions.setPassword(sender.password.toCharArray());
            mqttConnectOptions.setConnectionTimeout(sender.timeout);
            mqttConnectOptions.setKeepAliveInterval(20);
            var mqttClient = new MqttClient(String.format("tcp://%s:%d", sender.ip, sender.port), sender.clientId,
                memoryPersistence);

            mqttClient.connect(mqttConnectOptions);
            var mqttMessage = new MqttMessage(new Base64(sender.message.bytes).encode());
            mqttMessage.setQos(sender.qos.value);
            mqttMessage.setRetained(sender.retain);
            mqttClient.publish(sender.topic, mqttMessage);
            LOG.debug("clientId: {} 发送成功", sender.clientId);
            mqttClient.disconnect; // 这个位置可以要修改
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    def static void main(String[] args) {
        var ms = new MQTTSender();
        ms.publish(
            new SenderEntity("topic1").retain(true).ip("127.0.0.1").message("Hello World").username("admin").password(
                "123456")
        );
    }
}
